
const HttpUtil = require("./baseHttpUtil.js");
const ApiUrl = require("./baseApiUrl.js");
const Constant = require("./constant.js");


// 打开 momo app
const openMomoApp = () => {
    let pckName = app.getPackageName("MoMo");
    console.log(Constant.UI_SDK_VERSION + "打开: MomoPay App: ", pckName);

    // com.consumerug
    app.launchPackage(pckName)

    console.log(Constant.UI_SDK_VERSION + "等待10秒");
    sleep(10 * 1000);
}


// 退出 momo app
const closeMomoApp = () => {
    let pckName = app.getPackageName("MoMo");
    //强制停止 momo com.consumerug
    console.log(Constant.UI_SDK_VERSION + "强制停止 momo app: ", pckName);

    app.openAppSetting(pckName);
    text(app.getAppName(pckName)).waitFor();
    sleep(500);
    click("强行停止")
    console.log(Constant.UI_SDK_VERSION + app.getAppName(pckName) + "应用已被关闭");
    sleep(2 * 1000);
    click("确定");
    sleep(2 * 1000);
    back();
    sleep(5 * 1000);
}

// 开始查询数据
const getBillDetails = () => {
    // 判断是否为流水列表页
    // if (!PageUtil.isTransactionListPage()) {
    //     events.emitter().emit(PageTag.SESSION_TIME_OUT);
    //     return;
    // }

    let detailInfo = {
        currentBalance: "",
        mno:"momo",
        phone: Constant.getMtn(),
        bills: []
    }

    const currentBalanceText = "Current balance"
    const yourLast10TransacitonsText = "YOUR LAST 10 TRANSACTIONS"

    let textList = className("TextView").find();
    console.log(Constant.UI_SDK_VERSION + "找到了内容数 ", textList.length)

    for (let index = 0; index < textList.length; index++) {
        console.log(Constant.UI_SDK_VERSION + "当前 ", index)
        let tv = textList[index];
        let curText = tv.text()
        console.log(Constant.UI_SDK_VERSION + "内容 ", curText)

        if (curText !== "") {
            // 1、找到 Current balance
            if (curText.indexOf(currentBalanceText) !== -1) {
                const currentBalanceValueTv = textList[(index + 1)];
                detailInfo.currentBalance = currentBalanceValueTv.text() || "";

                console.log(Constant.UI_SDK_VERSION + "找到了 ", currentBalanceText)
                console.log(Constant.UI_SDK_VERSION + "============")
            }

            // 2、找到 YOUR LAST 10 TRANSACTIONS
            if (curText.indexOf(yourLast10TransacitonsText) !== -1) {
                console.log(Constant.UI_SDK_VERSION + "找到了 ", yourLast10TransacitonsText)
                console.log(Constant.UI_SDK_VERSION + "============")

                // 0 dateTime
                const dateTimeIndex = (index + 1);
                if (textList.length > dateTimeIndex) {
                    // 递归查询下一个菜单
                    const nextBillItemNext = dateTimeIndex;
                    getNextBillItemV2(textList, nextBillItemNext, detailInfo);
                }

                // 输出所有内容
                console.log(Constant.UI_SDK_VERSION + "输出所有内容: ")
                console.log(detailInfo)
                // 跳出循环，结束
                break;
            }
        }
    }

    console.log(Constant.UI_SDK_VERSION + "等待2秒")
    sleep(2000)
    // 保存数据
    console.log(Constant.UI_SDK_VERSION + "开始保存流程信息")
    let url = ApiUrl.saveBills();
    HttpUtil.sendPostSync(url, detailInfo)

    detailInfo.bills.length = 0;
    detailInfo.bills = [];

    textList.length = 0;
    textList = null;
    console.log(Constant.UI_SDK_VERSION + "上传数据中, 等待5秒")
    sleep(5 * 1000);
}

// 递归查询下一个菜单
const getNextBillItemV2 = (textList, dateTimeIndex, resultDetailInfo) => {
    console.log(Constant.UI_SDK_VERSION + "递归查询下一个菜单V2")
    if (textList && textList.length > dateTimeIndex) {
        // 0 dateTime
        let dateTimeTv = textList[dateTimeIndex];

        // 账单信息
        let billItem = {
            dateTime: "",
            amount: "",
            name: "",
            txnId: "",
            type: "",
            txnFee: "",
            toAddr: Constant.getMtn(),
            fromAddr: "",
            phone: Constant.getMtn()
        };
        billItem.dateTime = (dateTimeTv.text() || "").trim();

        // 是否为支出
        let isPayOut = true;

        // 1 amount
        let amountIndex = (dateTimeIndex + 1);
        if (textList.length > amountIndex) {
            let amountTv = textList[amountIndex];
            billItem.amount = amountTv.text() || "";

            // 收入
            if (billItem.amount.startsWith("+")) {
                isPayOut = false;
            }
        }

        if (isPayOut) {
            billItem.fromAddr = Constant.getMtn();
        }

        // 2 name
        let nameIndex = (dateTimeIndex + 2);
        if (textList.length > nameIndex) {
            let nameTv = textList[nameIndex];
            billItem.name = nameTv.text() || "";
        }

        // name 下一个标记
        let nameIndexNext = (nameIndex + 1);

        // 一直找 txnid
        let txnIdIndex = -1;
        for (let i = nameIndexNext; i < textList.length; i++) {
            let findTv = textList[i];
            let findTvText = findTv.text() || "";

            // 如果碰到 -xxx/+xxx 就退出循环
            if (findTvText.startsWith("-")) {
                break;
            }
            if (findTvText.startsWith("+")) {
                break;
            }

            if (findTvText.indexOf("Txn ID") !== -1) {
                txnIdIndex = (i + 1);
                if (textList.length > txnIdIndex) {
                    let txnIdTv = textList[txnIdIndex];
                    billItem.txnId = txnIdTv.text() || "";
                }
            }
        }

        // 一直找 type
        let typeIndex = -1;
        for (let i = nameIndexNext; i < textList.length; i++) {
            let findTv = textList[i];
            let findTvText = findTv.text() || "";

            // 如果碰到 -xxx/+xxx 就退出循环
            if (findTvText.startsWith("-")) {
                break;
            }
            if (findTvText.startsWith("+")) {
                break;
            }

            if (findTvText.indexOf("Transaction type") !== -1) {
                typeIndex = (i + 1);
                if (textList.length > typeIndex) {
                    let txnIdTv = textList[typeIndex];
                    billItem.type = txnIdTv.text() || "";
                }
            }
        }

        // 一直找 txn fee
        let txnFeeIndex = -1;
        for (let i = nameIndexNext; i < textList.length; i++) {
            let findTv = textList[i];
            let findTvText = findTv.text() || "";

            // 如果碰到 -xxx/+xxx 就退出循环
            if (findTvText.startsWith("-")) {
                break;
            }
            if (findTvText.startsWith("+")) {
                break;
            }

            if (findTvText.indexOf("Txn fee") !== -1) {
                txnFeeIndex = (i + 1);
                if (textList.length > txnFeeIndex) {
                    let txnIdTv = textList[txnFeeIndex];
                    billItem.txnFee = txnIdTv.text() || "";
                }
            }
        }

        // 一直找 to
        let toIndex = -1;
        for (let i = nameIndexNext; i < textList.length; i++) {
            let findTv = textList[i];
            let findTvText = findTv.text() || "";

            // 如果碰到 -xxx/+xxx 就退出循环
            if (findTvText.startsWith("-")) {
                break;
            }
            if (findTvText.startsWith("+")) {
                break;
            }

            if (findTvText.indexOf("To:") !== -1) {
                toIndex = (i + 1);
                if (textList.length > toIndex) {
                    let txnIdTv = textList[toIndex];
                    billItem.toAddr = txnIdTv.text() || "";
                }
            }
        }

        // 一直找 from
        let fromIndex = -1;
        for (let i = nameIndexNext; i < textList.length; i++) {
            let findTv = textList[i];
            let findTvText = findTv.text() || "";

            // 如果碰到 -xxx/+xxx 就退出循环
            if (findTvText.startsWith("-")) {
                break;
            }
            if (findTvText.startsWith("+")) {
                break;
            }

            if (findTvText.indexOf("From:") !== -1) {
                fromIndex = (i + 1);
                if (textList.length > fromIndex) {
                    let txnIdTv = textList[fromIndex];
                    billItem.fromAddr = txnIdTv.text() || "";
                }
            }
        }

        // 添加账单
        if (resultDetailInfo.bills === null) {
            resultDetailInfo.bills = []
        }
        resultDetailInfo.bills.push(billItem)


        // 最后查找 date 
        let nextBillItemNext = textList.length;
        for (let i = nameIndexNext; i < textList.length; i++) {
            let findTv = textList[i];
            let findTvText = findTv.text() || "";

            // 如果碰到 -xxx/+xxx 就退出循环
            if (findTvText.startsWith("-")) {
                nextBillItemNext = (i - 1);
                break;
            }
            if (findTvText.startsWith("+")) {
                nextBillItemNext = (i - 1);
                break;
            }
        }

        // 递归查询下一个菜单
        getNextBillItemV2(textList, nextBillItemNext, resultDetailInfo);

    } else {
        console.log(Constant.UI_SDK_VERSION + "递归结束, 没有更多")
    }
}

module.exports = {
    openMomoApp: openMomoApp,
    closeMomoApp: closeMomoApp,
    getBillDetails: getBillDetails
};